import { defineStore } from 'pinia'
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { GetUserInfoServer } from '@/api/instance'

export const useUserStore = defineStore('user',()=> {
  const userInfo = reactive({
    userId: 0,
    userAccount: '',
    userName: '',
    userRole:'',
    userCompany: '',
    userTelephone: '',
  })

  const changeUserRole=async (role)=>{
    userInfo.userRole = role;
  }

  const getUserInfo=async () => {
    try {
      const res = await GetUserInfoServer();
      if(res.code === 0){
        const getData = res.data;
        Object.assign(userInfo,getData);
      }else{
        ElMessage.error(res.message+'获取用户信息失败' || '获取用户信息失败');
      }
    }catch(error) {
      ElMessage.error(error.message+'网络请求失败' || '网络请求失败');
    }
  }
  
  const updateUserInfo=(newUserInfo)=>{
    Object.assign(userInfo,newUserInfo)
  }

  return {
    userInfo,
    changeUserRole,
    getUserInfo,
    updateUserInfo,
  }
}, 
{
  persist: true, // 持久化存储用户信息
}
)